# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

"""
Administrator account
add 
delete
modify  修改
...
"""


import time
import utils.pgsql.base.pgconn as pgconn

_tblName = "tbl_admin"

#   
_DB_SCRIPT = f"""
CREATE TABLE IF NOT EXISTS {_tblName} (
                "adminId"  SERIAL PRIMARY KEY ,
                "name" VARCHAR(260) NOT NULL default '' unique,
                "pwd"  VARCHAR(260) NOT NULL default '',
                "role" INTEGER NOT NULL default 0,         -- 1 system administrator  2 Channel administrator  3 case administrator  
                "operatorId" INTEGER NOT NULL default 0,
                "caseId" INTEGER NOT NULL default 0,
                "nickName" VARCHAR(260) NOT NULL default '',
                "phone" VARCHAR(260) NOT NULL default '',
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default '',
                "lastLoginTime" VARCHAR(32) NOT NULL default '',
                "caseroles" VARCHAR(260) NOT NULL default '0'   -- Scenic Area Authority Management
                );
                
insert into {_tblName} ("name", "pwd", "role" , "nickName", "phone", "createTime") values('admin','2c57282991e301c1c542f67396fed9d5',1,'系统管理员','12345678911','2021-09-08 00:00:00'); """


#  default passwd *Ab123456
# f"""insert into {_tblName} ("name", "pwd", "role" , "nickName", "phone", "createTime") values('admin','2c57282991e301c1c542f67396fed9d5',1,'系统管理员','12345678911','2021-09-08 00:00:00');"""


class PgAdmin:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create table
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

    
    def addAdmin(self, dic) -> str:
        print(dic)
        if "#" in dic["name"] or "-" in dic["name"]:
            return ""

        dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

        sql = f"""insert into {_tblName} ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"adminId"}" """
        return self._pgConn.exec_fetchone(sql)

 
    def modify(self, ids, dic) -> bool:
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])+ " \"adminId\" = '{}' ".format(ids)
        return self._pgConn.exec(sql)

    def lastlogin(self, ids) -> bool:
        dic = {"lastLoginTime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])+ " \"adminId\" = '{}' ".format(ids)
        return self._pgConn.exec(sql)

    def delete_city(self,id):
        sql = "delete from city where \"account_id\" = '{}' ".format(id)
        return self._pgConn.exec(sql)

    def update_city(self,id,dic):
        # dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql = "update city set {} where  ".format(sql_key[:-1]) + " \"account_id\" = '{}' ".format(id)
        return self._pgConn.exec(sql)

    def delete(self, ids) -> bool:
        sql = "delete from {} where \"adminId\" = '{}' ".format(_tblName, ids)
        return self._pgConn.exec(sql)

 
    def casedelete(self, ids) -> bool:
        sql = "delete from {} where \"caseId\" = '{}' ".format(_tblName, ids)
        return self._pgConn.exec(sql)

    def operatordelete(self, ids) -> bool:
        sql = "delete from {} where \"operatorId\" = '{}' ".format(_tblName, ids)
        print(sql)
        print(self._pgConn.exec(sql))
        return self._pgConn.exec(sql)

 
    def get_adminId(self, caseId) -> dict:
        sql = 'select  "adminId" from {} where "caseId" = \'{}\' order by "adminId" '.format(
            _tblName, caseId
        )
        return self._pgConn.exec_fetchone(sql)


    def get(self, ids) -> dict:
        sql = 'select a.*,n."operatorName" from {} a left join tbl_operator n on a."operatorId"=n."operatorId" where a."adminId" = \'{}\' order by a."adminId" '.format(
            _tblName, ids
        )
        return self._pgConn.exec_fetchone(sql)


    def get_name(self, name) -> dict:
        sql = 'select a."adminId",n."operatorName" from {} a left join tbl_operator n on a."operatorId"=n."operatorId" where "name" = \'{}\'order by a."adminId" '.format(
            _tblName, name
        )
        return self._pgConn.exec_fetchone(sql)

    def get_pwd(self, name) -> dict:
        sql = 'select "pwd" from {}  where "adminId" = \'{}\' '.format(_tblName, name)
        return self._pgConn.exec_fetchone(sql)

    def get_caseId(self, name) -> dict:
        sql = 'select "caseId" from {}  where "adminId" = \'{}\' '.format(
            _tblName, name
        )
        return self._pgConn.exec_fetchone(sql)

    def get_city_cases(self,admin_id):
        sql = f'select * from city where account_id={admin_id}'
        return self._pgConn.exec_fetchone(sql)


    def all(self) -> list:
        sql = 'select a.*,n."operatorName",c."caseName",d."caseName" AS "case_list",d."grantDate" from {} a ' \
              'left Join tbl_operator n on a."operatorId"=n."operatorId" ' \
              'left join tbl_case c on a."caseId"=c."caseId" ' \
              'left join city d on a."adminId"=d."account_id" where n."dataValid" !=0 or c."dataValid" !=0  order by a."adminId"'.format(
            _tblName
        )
        return self._pgConn.exec_fetchall(sql)

    def login(self, loginInfo) -> dict:

        if "#" in loginInfo["name"] or "-" in loginInfo["name"]:
            return {}
        else:
            # sql = f"""select * from {_tblName} where "name"= '{loginInfo['name']}' and "pwd"='{loginInfo['pwd']}' """
            sql = f"""select a.*,n."dataValid",c."dataValid",d."caseName" AS "case_list",d."grantDate" from  {_tblName} a 
                    left join tbl_operator n on a."operatorId"=n."operatorId" 
                    left join tbl_case c on a."adminId"=c."adminId"  
                    left join city d on a."adminId"=d."account_id"
                    where  a."name"= '{loginInfo['name']}' and a."pwd"='{loginInfo['pwd']}' and (c."dataValid" !=0 or n."dataValid" !=0 or a."name"='admin')  """

        return self._pgConn.exec_fetchone(sql)

